import PlatformBase from './PlatformBase';
import { GameConfig } from '../../Config/GameConfig';
import { CallBackHandler } from '../PoolObj/CallBackHandler';
import { NowTime } from '../../../Game/Config/ConstData';
import { GameData } from '../../Manager/DataManager';
import { GlobalParams, PlayerParams } from '../../Config/DataConfig';
import { HandleCode } from '../../Handle/Handler';
import { HandlerManager } from '../../Handle/HandlerManager';
import { AudioManager } from '../../Manager/AudioManager';
import { MainModel_Ins } from '../../../Game/Main/MainModel';
import { SoundCode } from '../../Config/BaseEnum';
/* eslint-disable */
// declare let wx: any;

export default class WXPlatform extends PlatformBase {
  shareImgId: string = '';
  shareImgUrl: string = '';
  firstTime: number;
  resumeBannerTimer: number = -1;
  /**
   * "补充账号信息
账号名称：冲关大侠
appid：wx7707d6bcd5a39716
激励广告ID:adunit-1ca00660febf093a
引力token:Kes2EhaWeugHNpCFGiql6j7sk4bTXRDo"
   */
  initFramework() {
    this.$videoId = 'adunit-1ca00660febf093a';
    this.$videoAd = null;
    this.$bannerId = '';
    this.$insertId = '';
    this.firstTime = NowTime();
    window['ad'] = false;
    window['insertAd'] = false;
    this.platformApi = window['wx'];
    try {
      this.systemInfo = window['wx'].getSystemInfoSync();
    } catch (e) {
      window['wx'].getSystemInfo({
        success(res) {
          this.systemInfo = res;
        },
      });
    }

    this.registerEvent();
  }

  registerEvent() {
    // console.log(wx, window['wx'].onShareAppMessage);

    const self = this;

    window['wx'].showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
    });

    window['wx'].updateShareMenu({
      withShareTicket: true,
      success() {},
    });

    window['wx'].onShareAppMessage(() => {
      // 用户点击了“转发”按钮
      const share = {
        title: '代码调用分享',
        imageUrl: self.shareImgUrl, // 图片 URL
        query: 'key1=val1&key2=val2',
      };
      const data = window['wx'].uma.trackShare(share);
      return data;
    });

    window['wx'].onUserCaptureScreen(() => {
      // 用户截屏了
      window['wx'].showShareImageMenu({
        path: '',
      });
    });

    window['wx'].onShow(() => {});
    // this.login();
    // setInterval(this.checkSession, 60);
  }

  getAppid() {
    // @ts-ignore
    return window['wx'].getAccountInfoSync().miniProgram.appId;
  }

  /** 登录 */
  login(callback?: CallBackHandler) {
    this.$loginCallback = callback;
    const self = this;
    window['wx'].login({
      success(res) {
        if (res?.code) {
          self.$appCode = res.code;
          // 发起网络请求
          // window['wx'].request({
          //   url: 'https:// example.com/onLogin',
          //   data: {
          //     code: res.code,
          //   },
          // });
          // WebRequestHttp.requestPost('https://cygame-platform.cygame666.cn/wx/openid/get', { appid: self.getAppid(), code: self.$appCode }, (data) => {
          // console.log('get openId', JSON.stringify(data));
          // if (data?.res?.openid != '') GameData.changePlayerAttr(PlayerParams.openId, data.res.openid, true);
          self.$loginCallback?.execute({ code: self.$appCode });
          HandlerManager.Ins().handle(HandleCode.MAIN_SIGNIN, self.$appCode);
          // self.getSetting();
          // });
        } else {
          // console.log('登录失败！' + res.errMsg);
          self.checkSession();
        }
      },
    });
  }

  /** 检测登录状态 */
  checkSession() {
    const self = this;
    window['wx'].checkSession({
      success() {
        // session_key 未过期，并且在本生命周期一直有效
        // if (constD.inGameState == 0) constD.inGameState = 1;
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        self.login(); // 重新登录
      },
    });
  }

  getSetting() {
    const self = this;
    window['wx'].getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          self.getUserInfo();
        } else {
          // 否则，先通过 window['wx'].createUserInfoButton 接口发起授权
          let button = window['wx'].createUserInfoButton({
            type: 'text',
            text: '',
            style: {
              left: 0,
              top: 0,
              width: 2000,
              height: 2000,
              lineHeight: 40,
              backgroundColor: '#ff000000',
              color: '#ffffff',
              textAlign: 'center',
              fontSize: 16,
              borderRadius: 4,
            },
          });
          button &&
            button.onTap((res) => {
              // 用户同意授权后回调，通过回调可获取用户头像昵称信息
              button.destroy();
              if (res.errMsg.indexOf(':ok') > -1 && !!res.rawData) self.getUserInfo();
            });
        }
      },
    });
  }

  loadUserInfo() {
    this.getSetting();
  }

  getUserInfo() {
    const self = this;
    window['wx'].getUserInfo({
      success(res) {
        // 此处可以获取到用户信息
        var userInfo = res.userInfo;
        var nickName = userInfo.nickName;
        var avatarUrl = userInfo.avatarUrl;
        var gender = userInfo.gender; //性别 0：未知、1：男、2：女
        var province = userInfo.province;
        var city = userInfo.city;
        var country = userInfo.country;
        GameData.changePlayerAttr(PlayerParams.getUserInfo, true, true);
        GameData.changePlayerAttr(PlayerParams.nickname, userInfo.nickName, true);
        GameData.changePlayerAttr(PlayerParams.avatarUrl, userInfo.avatarUrl, true);
        HandlerManager.Ins().handle(HandleCode.USERS_UPDATEINFOCACHE);
      },
      fail(res) {
        // self.$loginCallback?.execute({ code: self.$appCode });
        // HandlerManager.Ins().handle(HandleCode.MAIN_SIGNIN, self.$appCode);
      },
    });
  }

  /** 试玩结束提前下发奖励 */
  notifyMiniProgramPlayableStatus() {
    window['wx'].notifyMiniProgramPlayableStatus({ isEnd: true });
  }

  /** 直接转发 */
  shareMessage() {
    const self = this;
    window['wx'].shareAppMessage({
      // title: '转发标题',
      imageUrlId: self.shareImgId,
      imageUrl: self.shareImgUrl,
    });
  }

  openVibrateShort() {
    GameData.globalParams.get(GlobalParams.gameShark) &&
      window['wx'].vibrateShort({
        type: 'heavy',
        success() {
          // console.log('ovs s');
        },
        fail() {
          // console.log('ovs f');
        },
        complete() {
          // console.log('ovs c');
        },
      });
  }

  openVibrateLong(t: number = 15) {
    // gameD.SharkState &&
    GameData.globalParams.get(GlobalParams.gameShark) &&
      window['wx'].vibrateShort({
        type: 'heavy',
        success() {
          // console.log('ovs s');
        },
        fail() {
          // console.log('ovs f');
        },
        complete() {
          // console.log('ovs c');
        },
      });
  }

  sendDesktop(e) {}
  /** 调起添加桌面图标 */

  hasShortcutInstalled(e) {}
  /** 是否已添加桌面图标 */
  getIsDesktop() {}
  /** 播放音乐 */

  playMusic(e, t) {}
  /** 暂停音乐播放 */
  stopMusic() {}
  /** 播放音效 */

  playSound(e, t) {}
  /** 暂停音效 */

  stopSound(e) {}
  /** 退出游戏 */
  exitGame() {}
  /** 提示窗口 */

  showToast(e, i, d) {}
  createLupingBtn() {}
  createMoreGameBtn() {}

  loadBanner(bIndex: number) {}

  resumeBanner() {}

  showBanner(isShow: boolean) {
    const self = this;
    if (isShow) {
      if (this.$bannerAd)
        if (this.$bannerAd[0]) this.$bannerAd[0].show();
        else self.loadBanner(0);
    } else if (this.$bannerAd) {
      if (this.$bannerAd[0]) this.$bannerAd[0].hide();
      else {
        this.resumeBannerTimer > 0 && clearTimeout(this.resumeBannerTimer);
        // this.resumeBannerTimer = setTimeout(this.resumeBanner, 4200);
        if (this.$bannerInit) {
          this.$bannerInit = false;
          this.loadBanner(0);
        }
      }
    }
  }

  openBanner(e) {}
  hideBanner() {}

  protected startShowVideo() {
    const self = this;
    if (window['ad']) {
      // ManagetCtrl.Ins.uiMgr.showAlert('请勿频繁点击');
      console.log('请勿频繁点击', this.$adIndex);
      return;
    }
    // AudioManager.Singleton.bgmAudioSource.pause();

    window['ad'] = true;
    setTimeout(() => {
      window['ad'] = false;
    }, 2000);
    const obj = {
      adUnitId: this.$videoId,
    };
    AudioManager.Singleton.pauseMusic();
    if (this.$videoAd == null) {
      this.$videoAd = window['wx'].createRewardedVideoAd(obj);
      const onLoad = () => {
        // ManagetCtrl.Ins.uiMgr.showAlert('观看完成可获得激励');
        console.log('观看完成可获得激励');
        // self.$videoAd.show();
        self.showVideoSuccess();
      };

      const onError = (res: any) => {
        // ManagetCtrl.Ins.uiMgr.showAlert('正在加载视频广告');
        console.log('正在加载视频广告');
        console.log(res.errMsg, res.errCode);
      };

      const onClose = (res: any) => {
        console.log('用户关闭广告', JSON.stringify(res));
        // self.resumeBgm();
        // MainModel_Ins.adClose = true;
        // this.adClose = true;
        AudioManager.Singleton.loadAndPlayMusic(SoundCode.Bgm, true);
        // MainModel_Ins.adTimeLock = false;
        if (res.isEnded) {
          // do something
          // ManagetCtrl.Ins.uiMgr.showAlert('成功获取激励奖励');
          self.adFinish();
          self.showToast('获得广告奖励', '', 1000);
        } else {
          console.log('用户未看完广告');
          self.showToast('未看完广告,无法获取奖励', '', 1000);
        }

        // AudioManager.Singleton.bgmAudioSource.play();
        // AudioManager.Singleton.resumeBgmMusic();
        // setTimeout(() => {
        //   AudioManager.Singleton.resumeBgmMusic();
        // }, 1000);
        // if (res.count) {
        //   // 在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
        //   // 判断观看了几次广告
        // }
      };
      // this.$videoAd.offLoad(onLoad.bind(this));
      // this.$videoAd.offError(onError.bind(this));
      // this.$videoAd.offClose(onClose.bind(this));

      this.$videoAd.onLoad(onLoad.bind(this));
      this.$videoAd.onError(onError.bind(this));
      this.$videoAd.onClose(onClose.bind(this));
    }
    this.$videoAd.show().catch(() => {
      // 失败重试
      this.$videoAd
        .load()
        .then(() => this.$videoAd.show())
        .catch((err) => {
          console.error('激励视频 广告显示失败', err);
        });
    });
    return true;
  }

  resumeBgm() {
    return new Promise(function (resolve, reject) {
      AudioManager.Singleton.resumeBgmMusic();
    });
  }

  showInsertAd() {}

  loadNativeAd(e) {}

  showNativeInBox(e, t, i) {}

  showNativeInsert(e, t) {}

  showNativeInsertAd(e, i, a) {}

  showNativeBannerAd(e, i, a) {}

  showSmallNative(e) {}
  recordScreen() {}
  removeScreen() {}
  pauseRecord() {}

  showTTBanner(e) {}

  reportRankingList(e) {}
  getRankingList() {}
  showQQBox() {}

  navigateToVideo(e) {}
  jumpToDY() {}
  // eslint-disable-next-line @typescript-eslint/ban-types
  loadSubpackage(bundleName: string, callback: () => unknown = null) {
    const loadTask = window['wx'].loadSubpackage({
      name: bundleName, // name 可以填 name 或者 root

      success(res) {
        // 分包加载成功后通过 success 回调
        callback && callback();
      },

      fail(res) {
        // 分包加载失败通过 fail 回调
      },
    });

    loadTask.onProgressUpdate((res) => {
      // console.log('下载进度', res.progress);
      // console.log('已经下载的数据长度', res.totalBytesWritten);
      // console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
    });
  }

  showElectPortalAd(e) {}

  showwxCustomAd(e, t) {}

  openContent(e, t) {}
  closeContent() {}

  showNativeIcon(e, t) {}

  showNativeBanner(e, t) {}

  showPlayBanner(e) {}
  getHttpId() {}

  onHasShortcutInstalled(e) {}
  trackEvent(e, o = null) {
    window['wx'].uma && window['wx'].uma.trackEvent(e, o);
  }

  requestHttpGet(url: string, data: any, callback: CallBackHandler, headers?: { [key: string]: string }): void {
    window['wx'].request({
      method: 'GET',
      url: url,
      data: data,
      success(res) {
        callback.execute(res.data);
      },
    });
  }

  requestHttpPost(url: string, data: any, callback: CallBackHandler, headers?: { [key: string]: string }): void {
    window['wx'].request({
      method: 'POST',
      url: url,
      data: data,
      success(res) {
        callback.execute(res.data);
      },
    });
  }
}
